package com.heima.search.service.impl;

import com.heima.common.dto.ResponseResult;
import com.heima.common.util.UserThreadLocal;
import com.heima.search.dto.ApArticleSearchDto;
import com.heima.search.entity.ApUserSearch;
import com.heima.search.service.IApUserSearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ApUserSearchServiceImpl implements IApUserSearchService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    @Async
    public void saveSearchRecord(Integer userId, String searchWords,String equipmentId) {
        System.out.println("当前线程的名称："+Thread.currentThread().getName());
        // 判断当前用户查询的关键词是否已经有记录
        Query query = new Query();
        Criteria criteria = Criteria.where("keyword").is(searchWords);
        if (userId==0) {
            criteria.and("equipmentId").is(equipmentId);
        }else{
            criteria.and("userId").is(userId);
        }
        query.addCriteria(criteria);

        ApUserSearch userSearch = mongoTemplate.findOne(query, ApUserSearch.class);
        if(userSearch==null){
            userSearch = new ApUserSearch();
            userSearch.setUserId(userId);
            userSearch.setEquipmentId(equipmentId);
            userSearch.setKeyword(searchWords);
            userSearch.setCreatedTime(new Date());
            mongoTemplate.save(userSearch);
        }

//        select * from biaoming where equipmentId=?? and Keyword=??
//        select * from biaoming where UserId=?? and Keyword=??
    }

    public ResponseResult loadHistory(ApArticleSearchDto dto) {
        Integer userId = UserThreadLocal.get().getUserId();

        Query query = new Query();
        Criteria criteria = new Criteria();
        if (userId==0) {
            criteria.and("equipmentId").is(dto.getEquipmentId());
        }else{
            criteria.and("userId").is(userId);
        }
        query.addCriteria(criteria);

        query.with(Sort.by(Sort.Direction.DESC,"createdTime"));
        query.limit(5);
        List<ApUserSearch> apUserSearchList = mongoTemplate.find(query, ApUserSearch.class);

        return ResponseResult.okResult(apUserSearchList);
    }

    public ResponseResult delHistory(ApArticleSearchDto dto) {
        List<String> idList = dto.getHisList().stream().map(his -> {
            return his.getId();
        }).collect(Collectors.toList());

        Query query = new Query(Criteria.where("_id").in(idList));
        mongoTemplate.remove(query,ApUserSearch.class);

        return ResponseResult.okResult();
    }
}
